<!--
+----------------------------------------------------------------------
| 友得云客  - 开启房产营销新纪元
+----------------------------------------------------------------------
| Copyright (c) 2019~2023 优得（西安）信息科技有限公司版权所有
+----------------------------------------------------------------------
| Licensed 友得云客不是自由软件 未经允许不可移除相关版权
+----------------------------------------------------------------------
| Author: www.youdeyunke.com
+----------------------------------------------------------------------
-->
<!-- 
module box 组件主要实现组件的显示、处理选中状态、移动、删除
sub module box 组件主要实现嵌套子组件的显示、处理选中状态，移动删除等，由module box组件负责
-->
<template>
  <div class="mobile" v-cloak v-if="pageId">
    <AuxiliaryLine ref="fzLine" ></AuxiliaryLine>
    <div class="page" v-if="pageConfig">
      <div
        class="page-body-bg"
        :style="{ backgroundColor: bgColor, filter: bgBlur }"
      >
        <img v-if="bgImage" :src="bgImage" />
      </div>
      <div
        :class="{ 'page-title': true, 'page-title-active': titleActive }"
        @click.stop="titleClickHandle"
      >
        <page-title :title="pageConfig.title"></page-title>
      </div>
      <draggable
        element="div"
        ref="draggableContainer"
        v-model="pageModules"
        class="module-items module-items-page-style-fill"
        :forceFallback="true"
        :delay="100"
        animation="500"
        dragClass="drag-class"
        ghostClass="ghost-class"
        :style="{height: bodyHeight }"
        :options="{ filter: '.sticky' }"
        @start="dragging = true"
        @end="onDragEnd"
      >
        <div
          @click.stop="moduleItemClickHandle(index)"
          :class="{ 'module-item': true, module: true, sticky: module.sticky && module.sticky.enable, }"
          :style="{top: module.sticky ? module.sticky.top + 'px' : '0px',  left: module.sticky ? module.sticky.left + 'px' : '0px'}"
          v-for="(module, index) in pageModules"
          v-bind:key="module.id"
        >
          <module-box
            :index="index"
            :max-index="pageModules.length - 1"
            :module="module"
            :shadow-config="pageConfig.shadowValue"
            :dragging="dragging"
            @move="moduleMoveHandle"
            @delete="moduleDeleteHandle"
          >
            <component :module="module" :is="module.name + '-module'"></component>
          </module-box>
        </div>
      </draggable>

      <div
        :class="{ 'page-tabbar': true, 'page-tabbar-active': tabbarActive }"
        @click.stop="tabbarClickHandle"
      >
        <page-tabbar></page-tabbar>
      </div>

    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { createLog } from "@/api/logs";
import PageTitle from "./PageTitle";
import PageTabbar from "./PageTabbar";
import Draggable from "vuedraggable";
import BannersModule from "./modules/BannersModule";
import ImageModule from './modules/ImageModule'
import VideoModule from './modules/VideoModule'
import ModuleBox from "./modules/Base/ModuleBox";
import TextModule from "./modules/TextModule";
import NavsModule from "./modules/NavsModule";
import SubModuleBox from "./modules/SubModuleBox";
import SearchbarModule from "./modules/SearchbarModule/Index";
import PostsModule from "./modules/PostsModule/Index";
import HousesModule from "./modules/HousesModule/Index"
import BrokersModule from './modules/BrokersModule/Index'
import BlankModule from "./modules/BlankModule/Index";
import NoticeModule from "./modules/NoticeModule/Index";
import NewsModule from "./modules/NewsModule/Index";
import ToursModule from './modules/ToursModule/Index';
import FollowModule from './modules/FollowModule'
import WebviewModule from "./modules/WebviewModule.vue";
import ZhaofangModule from './modules/ZhaofangModule'
import VideosModule from './modules/VideosModule/Index.vue'
import MyselfloginModule from './modules/MyselfloginModule.vue';
import BtnsModule from './modules/BtnsModule/index.vue';
import HotnewsModule from './modules/HotnewsModule/index.vue';
import NewslistModule from './modules/NewslistModule/index.vue';
import BlockModule from './modules/BlockModule/index.vue'
import ScoregoodModule from './modules/ScoregoodModule/index.vue';
import SigndataModule from './modules/SigndataModule/index.vue';
import AuctionhousesModule from './modules/AuctionHousesModule/Index.vue'
import AuxiliaryLine from './AuxiliaryLine.vue';

export default {
  components: {
    PageTitle,
    PageTabbar,
    Draggable,
    ModuleBox,
    BannersModule,
    ImageModule,
    VideoModule,
    BlankModule,
    NavsModule,
    NewsModule,
    PostsModule,
    HousesModule,
    SearchbarModule,
    TextModule,
    SubModuleBox,
    NoticeModule,
    BrokersModule,
    NewsModule,
    ToursModule,
    FollowModule,
    ZhaofangModule,
    WebviewModule,
    VideosModule,
    MyselfloginModule,
    BtnsModule,
    HotnewsModule,
    NewslistModule,
    BlockModule,
    AuxiliaryLine,
    ScoregoodModule,
    SigndataModule,
    AuctionhousesModule,
  },
  props: {},
  data() {
    return {
      dragging: false,
    };
  },

  mounted: function () {
    this.keyCodeForEvent();
  },
  watch: {
    pageModules: function (val) {
      // let hasLoginModule = val.some(module => module.name == 'myselflogin');
      // // 如果有的话，检查login module的位置是否是第一位，不是的话，移至第一位
      // if (hasLoginModule) {
      //   var index = val.findIndex(module => module.name == 'myselflogin');
      //   if (index !== 0) {
      //     // 使用 Vue 的方法来移动元素
      //     const loginModule = this.pageModules[index];
      //     this.pageModules.splice(index, 1);
      //     this.pageModules.unshift(loginModule);
      //   }
      // }

      // let hasnewslistModule = val.some(module => module.name == 'newslist' && module.isBottom == true);
      // // 如果有的话，检查newslist module的位置是否是最后一位，不是的话，移至最后一位
      // if (hasnewslistModule) {
      //   var index = val.findIndex(module => module.name == 'newslist' && module.isBottom == true);
      //   if (index !== val.length - 1) {
      //     // 使用 Vue 的方法来移动元素
      //     const newslistModule = this.pageModules[index];
      //     this.pageModules.splice(index, 1);
      //     this.pageModules.push(newslistModule);
      //   }
      // }
        this.$store.commit("pagemaker/setCurrentModule");
            // 获取 <draggable> 内部的 DOM 元素
        if(val.length){
          var _this = this

          setTimeout(() => {
            const draggableContainer = _this.$refs.draggableContainer.$el;

            // 添加滚动事件监听器
            draggableContainer.addEventListener("scroll", _this.handleScroll);
          }, 500);

        }

    },
  },

  computed: {
    pageId: function () {
      return this.$store.state.pagemaker.pageId;
    },
    pageKey: function () {
            return this.$store.state.pagemaker.pageKey;
        },
    pageModules: {
      get() {
        return this.$store.state.pagemaker.pageModules;
      },
      set(val) {
        this.updateModules(val);
      },
    },
    moduleIndex: {
      get() {
        return this.$store.state.pagemaker.currentModuleIndex;
      },
      set(val) {
        if (typeof val != "number") {
          return;
        }

        console.log("fix module index in setter ", val);
        this.$store.commit("pagemaker/setCurrentModuleIndex", val);
      },
    },

    pageConfig: function () {
      return this.$store.state.pagemaker.pageConfig;
    },

    bodyHeight: function () {
      // TODO 处理底部导航栏高度
      var height = 810*2;
      height -= 100;
      return height + "px";
    },
    bgImage: function () {
      if (!this.pageConfig.bg) {
        return null;
      }
      var url = this.pageConfig.bg.image;
      return url;
    },

    bgBlur: function () {
      if (!this.pageConfig.bg) {
        return null;
      }
      if (this.pageConfig.bg.cat != "custom") {
        return null;
      }
      var p = this.pageConfig.bg.blur;
      return "blur(" + p + "px)";
    },


    bgColor: function () {
      //  页面背景色
      if (!this.pageConfig.bg) {
        return "#f9f9f9";
      }
      var color = "";

      color = this.pageConfig.bg.color;
      
      return color;
    },

    titleActive: function () {
      // 当前页面的标题是否显示为选中状态？
      // 当点击标题栏后，右侧编辑器切换为page，此时标题栏被选中
      return this.$store.state.pagemaker.focus === "page";
    },

    tabbarActive: function () {
      // 当前页面的tabbar是否显示为选中状态？
      // 当点击tabbar栏后，右侧编辑器切换为tabbar编辑，此时tabbar栏被选中
      return this.$store.state.pagemaker.focus === "tabbar";
    },

    toolbarConfig: function (index) {
      // module的工具条配置
      var c = { up: true, down: true, delete: true };
      c.up = index == 0 ? false : true;
      c.down = index == this.pageModules.length - 1 ? false : true;
      return c;
    },
  },
  methods: {
    subModuleSelectHandle: function (index, subIndex) {
      // 自由容器内部的子组件被选中
      // 向上传递给main组件控制
      // 为了防止，currentActive.moduleIndex 为null的情况
      // 因此要先将moduleIndex设置正确
      this.$emit("subModuleSelect", subIndex);
      console.log("page 中监听到子组件被点击", index, subIndex);
    },

    titleClickHandle: function () {
      // TODO update focus
      this.$store.commit("pagemaker/setFocus", "page");
    },
    tabbarClickHandle: function () {
      this.$store.commit("pagemaker/setFocus", "tabbar");
    },
    onDragEnd(e){
      this.dragging = false;
      console.log(e);
      var index = e.newIndex
      var operation = '管理员在' + this.pageKey +  '界面移动了'  + this.pageModules[index].label + '组件'
      createLog({
          type: '界面设计器管理',
          operation: operation
      }).then(() => { })
    },
    moduleDeleteHandle: function (index) {
      // 删除组件
      var msg = "确定要从该页面中删除这个组件吗？";
      this.$confirm(msg).then((_) => {
        var modules = this.pageModules;
        var operation = '管理员在' + this.pageKey +  '界面删除了'  + this.pageModules[index].label + '组件'
        modules.splice(index, 1);
        this.updateModules(modules);
        
        console.log(operation);
        createLog({
            type: '界面设计器管理',
            operation: operation
        }).then(() => { })
        // 如果删除后，index超过限度
        if (this.moduleIndex > modules.length - 1) {
          this.moduleIndex = modules.length - 1;
        }
      });
    },
    moduleItemClickHandle: function (index) {
      // 当模块被选中
      // 传递给 main 组件处理
      this.$emit("moduleSelect", index);
    },

    subModuleMoveHandle: function (subIndex, pos) {
      // 子组件移动
      console.log("move, sub index", subIndex, "pos", pos);
      var module = this.pageModules[this.moduleIndex];
      var subModule = module.children[subIndex];
      subModule.left = pos.left;
      subModule.top = pos.top;
    },
    subModuleDeleteHandle: function (subIndex) {
      // TODO 删除子组件
    },
    moduleMoveHandle: function (index, val) {
      // 判断是否能够移动
      var i = index;
      var j = index + val;
      if (j < 0) {
        return false;
      }
      if (j > this.pageModules.length - 1) {
        return false;
      }

      // 移动组件的顺序
      var page = this.page;
      var modules = this.pageModules;
      // 交换i,j的顺序
      var tmp = modules[i];
      modules[i] = modules[j];
      modules[j] = tmp;
      // 修改顺序后，moduleIndex改变
      console.log("+-val ", val);
      this.moduleIndex = index + val;
      this.updateModules(modules);
    },
    updateModules: function (modules) {
      this.$store.commit("pagemaker/setModules", modules);
    },

    moveUp: function () {
      // 将选中模块向上移动
      var i = this.moduleIndex;
      if (typeof i != "number") {
        return;
      }
      if (i == 0) {
        // 已经到顶
        return;
      }
      this.moduleMoveHandle(i, -1);
      this.moduleIndex = i - 1;
    },

    moveDown: function () {
      var i = this.moduleIndex;
      if (typeof i != "number") {
        return;
      }
      if (i == this.pageModules.length - 1) {
        return;
      }
      this.moduleMoveHandle(i, 1);
      this.moduleIndex = i + 1;
    },

    handleScroll(e){
                
      const draggableRect = this.$refs.draggableContainer.$el.getBoundingClientRect()
      this.$refs.fzLine.pageScroll(e.target.scrollTop, draggableRect)
    },

    keyCodeForEvent: function () {
      var _this = this;
      let ctrl = false;
      let up = false;
      let down = false;
      let del = false;
      // ctrl 17, up:38, down: 40
      document.onkeydown = function (e) {
        let evn = e || event;
        let key = evn.keyCode || evn.which || evn.charCode;
        console.log("key is", key);
        if (key === 17) {
          // ctrl
          ctrl = true;
        }
        if (key === 38) {
          // up
          up = true;
        }
        if (key === 40) {
          down = true;
        }

        if (key === 8) {
          del = true;
        }

        if (ctrl && up) {
          _this.moveUp();
          up = false;
        }
        if (ctrl && down) {
          _this.moveDown();
          down = false;
        }

        if (del) {
          //_this.moduleDeleteHandle(_this.moduleIndex);
          del = false;
        }
      };

      document.onkeyup = function (e) {
        if (e.keyCode === 17) {
          ctrl = false;
        }
        if (e.keyCode === 38) {
          up = false;
        }
        if (e.keyCode === 40) {
          down = false;
        }
      };
    },
  },
};
</script>

<style scoped>
::-webkit-scrollbar {
  width: 0px;
}

.page-title {
  cursor: pointer;
  height: 98px;
  line-height: 98px;
  border-bottom: 2px solid #eee;
  font-size: 34px;
  text-align: center;
  transition: all 0.5s;
}

.page-title-active,
.page-title:hover {
  border: 2px solid #1989fa;
  box-sizing: border-box;
}

.page-tabbar {
  height: 120px;
  line-height: 120px;
  border-bottom: 2px solid #eee;
  font-size: 34px;
  text-align: center;
  transition: all 0.5s;
  margin-top: 2px;
}

.page-tabbar-active,
.page-tabbar:hover {
  outline: 2px solid #1989fa;
  box-sizing: border-box;
}

.mobile {
  user-select: none;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
}

.mobile .module {
  box-sizing: border-box;
  font-size: 28px;
}

.module-item {
  position: relative;
  display: block;
  width: 100%;
  z-index:10,
}

.module-item.sticky{
  position: sticky;
  z-index:200;
}

.mobile .page {
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);
  width: 750px;
  height: 1624px;
  transform:scale(0.5);
  margin-top:-480px;
  position: relative;
  box-shadow: 4px 8px 20px rgba(0,0,0, 0.2);
}

.mobile {
  z-index: 0;
}

.mobile .sub-box {
  position: relative;
  width: 100%;
  height: 100%;
}

.module-items {
  overflow-y: scroll;
  transition: all 0.5s;
}

.page-body-bg {
  width: 100%;
  height: calc(100% - 100px);
  background-color: #f9f9f9;
  left: 0;
  top: 100px;
  right: 0;
  z-index: -1;
  position: absolute;
}

.page-body-bg img {
  width: 100%;
  height:auto;
}
.drag-class{
  /* zoom: 0.5; */
  display: none !important;
  /* border: 2px solid red; */
}
.ghost-class{
  color: red !important;
  border: 2px solid red;
  background: #eee;
}
</style>
